在前幾天的內容中,我們讓 App 能發送通知、儲存資料、呼叫 API。
但如果 App 要面向國際使用者,「多國語系(Localization)」就是不可或缺的功能。
今天將介紹:
這樣就完成語系設定,Xcode 會幫你建立對應的語系資料夾(如 zh-Hant.lproj
、en.lproj
)。
File → New → File → Strings File
Localizable.strings
Xcode 就會自動產生:
en.lproj/Localizable.strings
zh-Hant.lproj/Localizable.strings
在各語系檔案中,輸入對應文字:
en.lproj/Localizable.strings
"hello_message" = "Hello!";
"app_title" = "ITHelp Day23 APP";
"button_confirm" = "Confirm";
zh-Hant.lproj/Localizable.strings
"hello_message" = "你好!";
"app_title" = "ITHelp 第23天 APP";
"button_confirm" = "確認";
在 SwiftUI 中,只需要在 Text
或其他支援 LocalizedStringKey
的元件中
直接放入 key 即可自動對應語系。
import SwiftUI
struct LocalizationExampleView: View {
var body: some View {
VStack(spacing: 16) {
Text("hello_message")
.font(.title)
Text("app_title")
.font(.headline)
Button("button_confirm") {
print("Button tapped!")
}
}
.padding()
}
}
SwiftUI 會自動從當前系統語系載入對應的 Localizable.strings
。
SwiftUI Preview 也能直接切換語系:
#Preview {
ContentView().environment(\.locale, Locale(identifier: "zh_Hant"))
}
#Preview {
ContentView().environment(\.locale, Locale(identifier: "en"))
}
這樣就能在 Xcode 預覽不同語言顯示效果。
今天我們學會了:
Localizable.strings
Text("key")
自動對應語系到這裡,App 已經能根據系統語言自動顯示對應文字,讓使用者體驗更加貼近在地化。